#!/bin/bash

pwd=${PWD}

# 检查交叉编译器是否存在
if ! command -v aarch64-linux-gnu-gcc &> /dev/null; then
    echo "错误: aarch64-linux-gnu-gcc 未找到"
    echo "请安装交叉编译工具链: sudo apt install gcc-aarch64-linux-gnu g++-aarch64-linux-gnu"
    exit 1
fi

# 获取交叉编译器的完整路径
CC_FULL_PATH=$(which aarch64-linux-gnu-gcc)
CXX_FULL_PATH=$(which aarch64-linux-gnu-g++)

echo "使用C编译器: $CC_FULL_PATH"
echo "使用C++编译器: $CXX_FULL_PATH"

# 验证编译器可执行
if [ ! -x "$CC_FULL_PATH" ]; then
    echo "错误: C编译器不可执行: $CC_FULL_PATH"
    exit 1
fi

if [ ! -x "$CXX_FULL_PATH" ]; then
    echo "错误: C++编译器不可执行: $CXX_FULL_PATH"
    exit 1
fi

#x264
cd ${pwd}/3rd_party/x264
./x264_arm_debian_build.sh arm64

#ffmpeg
cd ${pwd}/3rd_party/ffmpeg
./build_ffmpeg_arm.sh arm64

#libyuv
cd ${pwd}/3rd_party/libyuv
./build_arm64.sh

cd ${pwd}/src

# 彻底清理构建目录和CMake缓存
echo "彻底清理构建环境..."
rm -rf build
rm -rf CMakeFiles
rm -f CMakeCache.txt
rm -f cmake_install.cmake
rm -f Makefile

mkdir build
cd build

# 设置环境变量
export CC=$CC_FULL_PATH
export CXX=$CXX_FULL_PATH

echo "开始配置ARM64交叉编译..."

# 使用完整路径显式设置编译器，强制清除缓存
cmake -DTARGET_ARCH=arm64 \
      -DCMAKE_C_COMPILER=$CC_FULL_PATH \
      -DCMAKE_CXX_COMPILER=$CXX_FULL_PATH \
      -DCMAKE_SYSTEM_NAME=Linux \
      -DCMAKE_SYSTEM_PROCESSOR=aarch64 \
      -DCMAKE_BUILD_TYPE=Release \
      ..

# 检查cmake是否成功
if [ $? -eq 0 ]; then
    echo "CMake配置成功，开始编译..."
    make -j8
else
    echo "CMake配置失败，查看错误日志"
    if [ -f CMakeFiles/CMakeError.log ]; then
        echo "=== CMakeError.log ==="
        cat CMakeFiles/CMakeError.log
    fi
    exit 1
fi

cd ${pwd}